Assignment: Looping, Matrices Due: Just run the examples. There is nothing due Discussion: There are often functions in R to do what you want. Often the task may take a short sequence of function. You may know what you want to do but not know the name of the R functions or the syntax for branching, etc. Below are descriptions or at least clues to many useful functions 1. Sequences 2. Looping 3. apply functions to an array 4. scaling matrix columns 5. sweeping arrays 6. tapply: apply a function to table cells 7. processing lists 8. tabling 9. matrix subscripts 10. matrix operations 11. data.frames, missing data and merging 12. branching 13. text and formatting functions 14. sampling 15. lattice construction 1. Sequences______________________________________________ ##Run 1:10 seq(1,10) seq(1,10,by=3) ## ##Run seq(0,2*pi,length=101) ## 2. Looping___________________________________________ Explicit looping is slow in R. Some of the R functions below have internally coded looping that runs much faster. Still, sometimes it is more convenient to code using loops. R has for() and while() statements for explicit looping. next to skip a cycle break to get out of the current loop 2.1 Simple for() loop ##Run mysum = 0 for (i in 1:10)mysum = mysum+i mysum ## ##Run mysum = 0 for (i in 1:10){ if(i==5)next mysum = mysum+i } mysum ## 2.2 Nested loops ##Run iBegin = 1 # constant iEnd = 5 # constant k = 0 # initial values mat = matrix(0,nrow=iEnd,ncol=iEnd) # define a matrix for (i in iBegin:(iEnd-1)){ for (j in (i+1):iEnd){ k = k+1 mat[i,j] = k } } mat ## 2.3 Looping through a list The syntax is for (i in listObject){} The index i will refer to each component of the listObject in turn and can be used in computations. 3. apply()______________________________________________ The first argument to apply is an array. The second argument controls array subsetting 1 means compute on the reduced array for as the first subscript steps through it values. For a matrix this mean compute on each row. 2 does the same for each value of the second subscript For a matrix this mean compute on each column. The third argument is the function to apply to the reduce array at each step. This can be an analyst written function. Additional arguments pass through as argument to function specified in the third argmument. For example the argument na.rm=T might be supplied to remove missing data. The function range()below returns the min and max of a vector. The returned object below, mat.r, is a matrix with two rows. The first row has the minimum of each column. The second row has the maximum of each column. ##Run mat = matrix(rnorm(49),ncol=7) mat.r = apply(mat,2,range) round(mat.r,2) ## We can find the midpoint of the range for each column by using the mean() and the max - min by using diff() ##Run cen = apply(mat.r,2,mean) round(cen,2) sc = apply(mat.r,2,diff) round(sc,2) ## 4. scale()_________________________________________ The following scales all columns in mat into values [-1,1]. The first argument is the input matrix The second is a vector whose elements are to subtracted from the respective columns. The third is a vector whose respective elements divide into corresponding columns. ##Run mat.sc1 = scale(mat, center=cen, scale=sc/2) round(mat.sc1,2) ## 5. sweep()___________________________________________ Provides a more general array capability The first two arguments are like those in apply(). The third argument is additional data to use. The forth gives the operation which is "-" by default. ##Run mat.sc2 = sweep(mat,2,apply(mat.r,2,mean)) #subtract the means from colums mat.sc2 mat.sc2 = sweep(mat.sc2,2,apply(mat.r,2,diff)/2,"/") #standardize mat.sc2 range(mat.sc2-mat.sc1) # a quick comparison of the two matrices ## 6. tapply()________________________________________ Applies a function to cells of a categorical table. ##Run # make a list of the classification factors Sex = c("M","F","M","M","F","F") Eyes = c("Brown","Blue","Blue","Brown","Brown","Brown") cellIndices = list(Sex,Eyes) # construct a dependent variable Weight = c(160,120,150,200,105,110) # compute the mean for each cell. weight.ave = tapply(Weight,cellIndices,mean,na.rm=T) weight.ave # The values might have been stored in a data frame people = data.frame(Weight,Sex,Eyes) # Then same results can be obtained using cellIndices = list(people$Sex,people$Eyes) weight.ave = tapply(people$Weight,cellIndices,mean,na.rm=T) weight.ave ## 7. Lists and processing lists______________________________________ 7.1 Creating lists ##Run: make list with a vector, a character string, and a matrix myList = list(x=c(1:4), lab ="A character string", mat=matrix(1:4,ncol=2)) myList$x myList$lab myList$mat ## split() split(data,group) creates list element using data for each unique element in group. If data is vector, the list elements are vectors If data is a matrix the list element are matrices whose rows have the same group membership. 7.2 processing lists sapply() and lapply() sapply() and lapply() apply a function to each top level element of a list. The result of lapply() is a list. The result of sapply may simplify to a vector or a matrix. ##Run weightByEye = split(people$Weight,people$Eye) weightByEye sapply(weightByEye,mean) ## 8. table()_____________________________________________________ Counting cases in the table cells. ##Run table(people$Sex,people$Eyes) ## 9. Matrix subscripts________________________________________ # logical subscripts ##Run i.end = 3 j.end = 4 mat2 = matrix(0,nrow=i.end,ncol=j.end) # define a matrix col(mat2) # returns matrix with column numbers row(mat2) # returns matrix with row numbers subs.logical = col(mat2) > row(mat2) subs.logical ## ##Run mat2[subs.logical] = 1:6 # Insert in the TRUE locations mat2 # R increase the row subscript fastest ## 10. Matrices and a few matrix operations__________________________ 10.1 Access the dimension attribute ##Run dim(mat) nrow(mat) ncol(mat) ## 10.2 Row and column names The dimnames are a list structure composed of two vectors whose elements are character strings. ##Run dimnames(mat) = list(paste("Row",1:nrow(mat),sep=''), paste("Col",1:ncol(mat),sep='')) dimnames(mat) dimnames(mat)[[1]] # row names dimnames(mat)[[2]] # column names ## 10.3 Construction from vectors ##Run v1 = rnorm(10) v2 = rnorm(10) v3 = rnorm(10) cbind(v1,v2,v3) # column binding ## ##Run # row binding rbind(v1,v2,v3)[,1:4] ## 10.3 Matrix Multiplication %*% is the matrix multiple operator. The example below sums the elements of each row. ##Run Sum rows of a matrix with matrix multiplication one = rep(1,ncol(mat)) # A vector of 1s tmp = mat %*% one tmp ## R treats vectors as either rows or columns. If the situation is not clear, as in x %*% x, R will use the inner product. To produce the outer product use x %o% x. 10.4 Removing rows with missing data ## Run mat[1,2] = NA tmp = mat %*% one tmp mat = mat[!is.na(tmp),] mat ## 11. Data.frames, missing data and merging______________________ 11.1 Data.frames have convenient options for handling missing data, na.omit() omits rows. A package contains na.gam.replace() that replaces the missing values with the average of the available data in missing items column. ##Run nmat = as.data.frame(matrix(rnorm(12),ncol=3)) nmat[1,2] = NA na.omit(nmat) # na.gam.replace(nmat) # must install package first ## 11.2 Merging data.frames ##Run nam = c('George','Henry','Sue','Sarah') score1 = c(94,95,91,99) score2 = c(15,NA,18,20) IQ = c(115,125,121,136) datFrame1 = data.frame(score1,row.names=nam) datFrame2 = data.frame(score2,IQ,row.names=nam) frameNew = merge(datFrame1,datFrame2,by="row.names") datFrame1 frameNew # the row.names become a column ## ##Run ?merge # there are many data frame merging options ## 12. Branching___________________________________________ 12.1 The if() syntax is pretty common if ( ) statement if ( ) { multiple lines } if ( ) statement else statement if ( ) { multiple lines } else { multiple lines } ##Run k = 5 m = 13 if(k <=7 & m <15) x = 1:5 else x = 6:10 x ## 12.2 ifelse ifelse () works on three vectors, a logical vector and two vectors of values. If the item is T for the logical vector the result comes from the corresponding value in the second column otherwise it comes from the third column. ##Run tst = c(1,3,9,16) result1 = c(1,2,3,4) result2 = c(11,12,13,14) ifelse(tst>3,result1,result2) ## To evalate one of several expression see switch ##Run ?switch ## 13. Some text and formatting functions__________________________ paste() nchar() substring() lowerCase() upperCase() format() round() cat() ##Run strings = paste('s',1:1000,sep='') n = nchar(strings) good = substring(strings,n-1,n)=="23" strings[good] ## ##Run for(i in 1:5)cat(i,fill=T) # print values from inside a loop ## 14. Sampling_________________________________________________ ##Run dat = rnorm(1000,mean=100,sd=16) # simulated IQ values samp1 = sample(dat,50,replace=T) # bootstrap sample samp2 = sample(dat,50,replace=T) cbind(samp1,samp2) ## ##Run scramble = sample(1:10,10,replace=F) scramble ## 15. Lattice construction___________________________________ ##Run mylist = list(x=1:4,y=1:3,z=1:4) ans = expand.grid(mylist) ans ##